const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("koa2-cors");
require("dotenv").config();
const habitRouter = require("./habit");
const todayRouter = require("./today");
const userRouter = require("./user");
const path = require("path");
const { uploadFileBuffer } = require("../utils/minio-client");
const app = new Koa();
const router = new Router();
const { exec } = require("child_process");
const { koaBody } = require("koa-body");
const fs = require("fs");

app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 100 * 1024 * 1024, // 最大100MB
      keepExtensions: true, // 保留文件扩展名
    },
  })
);

// 服务端支持跨域
app.use(
  cors({
    origin: function (ctx) {
      const requestOrigin = ctx.get("Origin");
      const whiteList = ["https://www.mayflower.chat", "http://localhost:5173"];
      if (whiteList.includes(requestOrigin)) {
        return requestOrigin;
      }
      return false;
    },
    credentials: true, // 允许跨域的时候带着 cookie
  })
);

// 自动部署
router.post("/webhook", async (ctx) => {
  ctx.body = { success: true, message: "部署已开始" };
  setTimeout(() => {
    exec("/var/www/wuxing-koa/deploy.sh", (error, stdout, stderr) => {
      if (error) {
        console.error("❌ 部署失败:", error.message);
        console.error(stderr);
      } else {
        console.log("✅ 部署成功:\n", stdout);
      }
    });
  }, 1000);
});

// 上传文件
router.post("/upload", async (ctx) => {
  const file = ctx.request.files?.file;
  if (!file) {
    ctx.status = 400;
    ctx.body = { error: "No file uploaded" };
    return;
  }
  let filePath, originalName, mimeType;
  if (file.filepath) {
    // 新版本koa-body格式
    filePath = file.filepath;
    originalName = file.originalFilename;
    mimeType = file.mimetype;
  } else if (file.path) {
    // 旧版本格式
    filePath = file.path;
    originalName = file.name;
    mimeType = file.type;
  } else {
    throw new Error("Unsupported file object format");
  }

  try {
    const fileBuffer = await fs.promises.readFile(filePath);
    const ext = path.extname(originalName);
    const fileName = `${Date.now()}${ext}`;
    const fileUrl = await uploadFileBuffer(fileName, fileBuffer, {
      "Content-Type": mimeType,
      "Original-Filename": originalName,
    });
    ctx.body = {
      success: true,
      url: fileUrl,
      fileName: fileName,
      originalName: originalName,
    };
  } catch (error) {
    console.error("Upload error:", error);
    ctx.status = 500;
    ctx.body = { error: "File upload failed", details: error.message };
  }
});

app.use(router.routes()).use(router.allowedMethods());
app.use(habitRouter.routes()).use(habitRouter.allowedMethods());
app.use(todayRouter.routes()).use(todayRouter.allowedMethods());
app.use(userRouter.routes()).use(userRouter.allowedMethods());
app.listen(9000, () => console.log(`🚀 http://localhost:9000`));
